package com.sealer.pattern.creational.singleton;

/**
 * Created by sealer on 17/03/29.
 * 这个是第二种方式的升级版，俗称双重检查锁定
 * jdk1.5才能使用双重校验, 因为jdk1.5才引入了修饰符volatile
 * 详见: http://www.ibm.com/developerworks/cn/java/j-dcl.html
 */
public class Singleton7 {
    private volatile static Singleton7 instance;

    private Singleton7() {
    }

    public static Singleton7 getInstance() {
        if (instance == null) {
            synchronized (Singleton7.class) {
                if (instance == null) {
                    instance = new Singleton7();
                }
            }
        }
        return instance;
    }

    /**
     * 有人说return应该写在同步块中， 写法如下：
     *
     * @return
     */
    public static Singleton7 getInstance2() {
        if (instance != null) {
            return instance;
        }
        synchronized (Singleton7.class) {
            if (instance == null) {
                instance = new Singleton7();
            }
            return instance;//return from here
        }
    }
}
